package com.sntk.organauthomanager.application.service;

import com.sntk.organauthomanager.application.dto.ResourceCreator;
import com.sntk.organauthomanager.application.dto.ResourceDTO;
import com.sntk.organauthomanager.domain.model.Resource;
import com.sntk.organauthomanager.domain.model.ResourceType;
import com.sntk.organauthomanager.domain.repository.ResourceRepository;
import com.sntk.organauthomanager.infrastructure.exception.ObjectNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

/**
 * @ClassName: ResourceApplicationService
 * @author: wgchao
 * @createTime: 2020/7/21 4:44 PM
 * @Description: TODO
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class ResourceApplicationService {
    @Autowired
    private ResourceRepository resourceRepository;

    /**
     * 创建资源
     * @param creator
     * @param operator
     */
    public void createResource(ResourceCreator creator, String operator){
        Resource parent = null;
        if(!StringUtils.isEmpty(creator.getParentResource())){
            parent = resourceRepository.findByKey(creator.getParentResource());
            if(parent == null){
                throw new ObjectNotFoundException("上级资源不存在");
            }
        }

        Resource resource = Resource.generate(creator.getMark(), creator.getName(), ResourceType.get(creator.getResourceType()),
                parent);
        resourceRepository.add(resource, operator);
    }

    /**
     * 修改资源信息
     * @param resourceDTO
     * @param operator
     */
    public void modifyResourceInfo(ResourceDTO resourceDTO, String operator){
        Resource resource = resourceRepository.findByKey(resourceDTO.getMark());
        if(resource == null){
            throw new ObjectNotFoundException("资源不存在");
        }
        resource.modifyMenuInfo(resourceDTO.getName(), resourceDTO.getDisabled());
        resourceRepository.add(resource, operator);
    }

    /**
     * 删除资源
     * @param mark
     * @param operator
     */
    public void removeResource(String mark, String operator){
        Resource resource = resourceRepository.findByKey(mark);
        if(resource == null){
            throw new ObjectNotFoundException("资源不存在");
        }
        resourceRepository.delete(mark, operator);
    }
}
